<?php namespace Poscms\Model;
/**
 * POSCMS框架文件
 * 二次开发时请勿修改本文件
 * 四川迅睿云软件开发有限公司 www.xunruicms.com
 */
class App extends \CI_Model {

    private $cfg_cache;

	/**
	 * 删除模块时调用
	 *
	 * @param	string	$module	模块目录
	 * @param	intval	$siteid	站点id，默认为全部站点
	 * @return  string
	 */
	public function delete_for_module($module, $siteid) {
	
	}
	
	/**
	 * 删除模块内容时调用
	 *
	 * @param	string	$module	模块目录
	 * @param	intval	$siteid	站点id，默认为全部站点
	 * @return  string
	 */
	public function delete_for_cid($cid, $module) {
	
	}
	
	/**
	 * 删除会员时调用
	 *
	 * @param	intval	$uid	会员uid
	 * @return  string
	 */
	public function delete_for_uid($uid) {
	
	}
	
	/**
	 * 将应用菜单安装至后台菜单中
	 *
	 * @param	string	$dir	应用目录名称
	 * @param	intval	$id		应用id
	 * @return  void
	 */
	public function install_admin_menu($dir, $id) {
		
	}
	
	/**
	 * 将应用菜单安装至会员菜单中
	 *
	 * @param	string	$dir	应用目录名称
	 * @param	intval	$id		应用id
	 * @return  void
	 */
	public function install_member_menu($dir, $id) {
		
	}


	// 安装phpcmf插件

    // 开始安装app
    public function install($dir) {

        $path = dr_get_app_dir($dir);
        if (!is_file($path.'Config/App.php')) {
            return dr_return_data(0, dr_lang('插件配置文件不存在'));
        }

        $config = require $path.'Config/App.php';

        // 执行sql语句
        if (is_file($path.'Config/Install.sql')) {
            $this->_query_all(str_replace('{dbprefix}',  $this->db->dbprefix, file_get_contents($path.'/Config/Install.sql')));
        }

        // 执行站点sql语句
        if (is_file($path.'Config/Install_site.sql')) {
            $sql = file_get_contents($path.'Config/Install_site.sql');
            foreach (\Poscms\Service::C()->site_info as $siteid => $a) {
                $this->_query_all(str_replace('{dbprefix}',  $this->db->dbprefix($siteid.'_'), $sql));
            }
        }

        // 执行模块自己的安装程序
        if (is_file($path.'Config/Install.php')) {
            require $path.'Config/Install.php';
        }

        // 创建菜单
        if (is_file($path.'Config/Menu.php')) {
            $menu = require $path.'Config/Menu.php';
            if ($menu['admin']) {
                // 后台菜单
                foreach ($menu['admin'] as $mark => $top) {
                    // 插入顶级菜单
                    $mark = strlen($mark) > 2 ? $mark : '';
                    $top_id = $top['name'] ? $this->_add_menu('admin', 0, $top, $mark) : $this->_get_id_for_mark('admin', $mark);

                    // 插入分组菜单
                    if ($top_id && $top['left']) {
                        foreach ($top['left'] as $mark2 => $left) {
                            $mark2 = strlen($mark2) > 2 ? $mark2 : '';
                            $left_id = $left['name'] ? $this->_add_menu('admin', $top_id, $left, $mark2) : $this->_get_id_for_mark('admin', $mark2);
                            // 插入链接菜单
                            if ($left_id) {
                                foreach ($left['link'] as $link) {
                                    if (\Phpcmf\Service::M()->counts('admin_menu', 'pid='.$left_id.' and `uri`="'.$link['uri'].'"')) {
                                        continue;
                                    }
                                    $this->_add_menu('admin', $left_id, $link);
                                }
                            }
                        }
                    }
                }
            }

            if ($menu['member']) {
                // 用户菜单
                foreach ($menu['member'] as $mark => $top) {
                    // 插入顶级菜单
                    $mark = strlen($mark) > 2 ? $mark : '';
                    $top_id = $top['name'] ? $this->_add_menu('member', 0, $top, $mark) : $this->_get_id_for_mark('member', $mark);
                    // 插入链接菜单
                    if ($top_id && $top['link']) {
                        foreach ($top['link'] as $mark2 => $link) {
                            if (\Phpcmf\Service::M()->counts('member_menu', 'pid='.$top_id.' and `uri`="'.$link['uri'].'"')) {
                                continue;
                            }
                            $this->_add_menu('member', $top_id, $link);
                        }
                    }

                }
            }
        }

        $this->db->insert('application', array(
            'module' => '',
            'dirname' => $dir,
            'setting' => '',
            'disabled' => 0,
        ));

        return dr_return_data(1, dr_lang('安装成功'));
    }

    // 更具mark获取id
    private function _get_id_for_mark($table, $mark) {

        if (!$mark) {
            return 0;
        }

        $data = $this->db->where('mark', $mark)->get($table.'_menu')->row_array();

        return (int)$data['id'];
    }

    // 新增菜单
    public function _add_menu($table, $pid, $data, $mark = '') {

        if (!$data['name'] && !$data['uri']) {
            return;
        }

        !$mark && ($mark = $data['mark'] ? $data['mark'] : '');

        if ($table == 'admin') {
            $this->db->insert('admin_menu', [
                'pid' => $pid,
                'name' => $data['name'],
                'uri' => $data['uri'] ? $data['uri'] : '',
                'url' => $data['url'] ? $data['url'] : '',
                'mark' => $mark,
                'icon' => $data['icon'] ? $data['icon'] : '',
                'hidden' => (int)$data['hidden'],
                'displayorder' => (int)$data['displayorder'],
            ]);
        } else {

            $this->db->insert('member_menu', [
                'pid' => $pid,
                'name' => $data['name'],
                'uri' => $data['uri'] ? $data['uri'] : '',
                'url' => $data['url'] ? $data['url'] : '',
                'mark' => $mark,
                'icon' => $data['icon'] ? $data['icon'] : '',
                'hidden' => (int)$data['hidden'],
                'displayorder' => (int)$data['displayorder'],
            ]);
        }

        return $this->db->insert_id();
    }

    // 卸载
    public function uninstall($dir) {

        $path = dr_get_app_dir($dir);
        if (!is_file($path.'Config/App.php')) {
            return dr_return_data(0, dr_lang('插件配置文件不存在'));
        }

        // 执行sql语句
        if (is_file($path.'Config/Uninstall.sql')) {
            $this->_query_all(str_replace('{dbprefix}',  $this->db->dbprefix, file_get_contents($path.'Config/Uninstall.sql')));
        }

        // 执行站点sql语句
        if (is_file($path.'Config/Uninstall_site.sql')) {
            $sql = file_get_contents($path.'Config/Uninstall_site.sql');
            foreach (\Poscms\Service::C()->site_info as $siteid => $a) {
                $this->_query_all(str_replace('{dbprefix}',  $this->db->dbprefix($siteid.'_'), $sql));
            }
        }

        // 执行自己的卸载程序
        if (is_file($path.'Config/Uninstall.php')) {
            require $path.'Config/Uninstall.php';
        }


        // 删除菜单

        $menu = require $path.'Config/Menu.php';
        if ($menu) {
            $this->app_admin_menu($menu);
            $this->app_member_menu($menu);
        }


        $this->db->where('mark', 'app-'.$dir)->delete('admin_menu');
        $this->db->where('mark', 'app-'.$dir)->delete('member_menu');

        $this->db->like('mark', 'app-'.$dir.'%')->delete('admin_menu');
        $this->db->like('mark', 'app-'.$dir.'%')->delete('member_menu');

        $this->db->where('dirname',$dir)->delete('application');
        return dr_return_data(1, dr_lang('卸载成功'));
    }

    public function app_member_menu($menu) {
        if ($menu['member']) {
            // 用户菜单
            foreach ($menu['member'] as $mark => $top) {
                // 插入顶级菜单
                // 插入顶级菜单
                $mark = strlen($mark) > 2 ? $mark : '';
                $top_id = $top['name'] ? $this->_add_menu('member', 0, $top, $mark) : $this->_get_id_for_mark('member', $mark);
                // 插入链接菜单
                if ($top_id && $top['link']) {
                    foreach ($top['link'] as $mark2 => $link) {
                        if (\Phpcmf\Service::M()->counts('member_menu', 'pid='.$top_id.' and `uri`="'.$link['uri'].'"')) {
                            continue;
                        }
                        $this->_add_menu('member', $top_id, $link);
                    }
                }
            }
        }
    }

    public function app_admin_menu($menu) {
        if ($menu['admin']) {
            foreach ($menu['admin'] as $mark => $top) {
                // 插入顶级菜单
                $mark = strlen($mark) > 2 ? $mark : '';
                $top_id = $top['name'] ? $this->_add_menu('admin', 0, $top, $mark) : $this->_get_id_for_mark('admin', $mark);

                // 插入分组菜单
                if ($top_id && $top['left']) {
                    foreach ($top['left'] as $mark2 => $left) {
                        $mark2 = strlen($mark2) > 2 ? $mark2 : '';
                        $fmark =  $mark2 ? $this->_get_id_for_mark('admin', $mark2) : '';
                        $left_id = $fmark ? $fmark : $this->_add_menu('admin', $top_id, $left, $mark2);
                        // 插入链接菜单
                        if ($left_id) {
                            foreach ($left['link'] as $link) {
                                if (\Phpcmf\Service::M()->counts('admin_menu', 'pid='.$left_id.' and `uri`="'.$link['uri'].'"')) {
                                    continue;
                                }
                                $this->_add_menu('admin', $left_id, $link);
                            }
                        }
                    }
                }
            }
        }
    }

    // 执行sql
    private function _query_all($sql) {

        if (!$sql) {
            return NULL;
        }

        $sql_data = explode(';SQL_FINECMS_EOL', trim(str_replace(array(PHP_EOL, chr(13), chr(10)), 'SQL_FINECMS_EOL', $sql)));

        foreach($sql_data as $query){
            if (!$query) {
                continue;
            }
            $ret = '';
            $queries = explode('SQL_FINECMS_EOL', trim($query));
            foreach($queries as $query) {
                $ret.= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
            }
            if (!$ret) {
                continue;
            }
            $this->db->query($ret);
        }
    }

    // 读取配置信息
    public function get_config($dir) {

        if (!$dir) {
            return [];
        }

        if (!isset($this->cfg_cache[$dir])) {
            $this->cfg_cache[$dir] = \Phpcmf\Service::L('Cache')->get_file($dir, 'app');
        }
        return $this->cfg_cache[$dir];
    }

    // 存储配置缓存
    public function save_config($dir, $data) {

        if (!$dir) {
            return 0;
        }

        \Phpcmf\Service::L('Cache')->set_file($dir, $data, 'app');
    }
	
}